define(function (require, exports, module) {
    var angular = require('angular');
    var util = require('util');
    require("angular-ui");
    require("angular-route");

    var beeTeamModule = angular.module('beeTeam', [])
        .constant('api.path.team', "/api/index.php?r=xmf/xmf-team/")
        .factory('TeamService', [
            '$http',
            'api.path.team',
            function ($http, api_path) {
                var httpClient = {
                    get: function (api, data) {
                        var url = api_path + api;
                        var search = (data && data.search) || {};
                        angular.forEach(search, function (val, key) {
                            url += "&" + key + "=" + val;
                        });

                        return $http.get(url)
                            .then(function (res) {
                                res = res.data;
                                if (res.retCode == "0") {
                                    return res;
                                }
                            })
                    },
                    post: function (api, data) {
                        return $http.post(api_path + api, (data && data.data) || {})
                            .then(function (res) {
                                res = res.data;
                                if (res.retCode == "0") {
                                    return res;
                                }
                            })
                    }                    
                }
                return {
                    getMemberList: function (search) {
                        return httpClient.get('member-list', search)
                    },
                    getMembers: function (search) {
                        return httpClient.get('add-list', search)
                    },
                    searchMembers: function (search) {
                        return httpClient.get('search-user', search)
                    },
                    createUser: function (data) {
                        return httpClient.post('add-user', data)
                    },
                    updateUser: function (data) {
                        return httpClient.post('edit-user', data)
                    },
                    deleteUser: function (data) {
                        return httpClient.post('del-user', data)
                    },
                    getTemplateUrl: function () {
                        return api_path + "download-template";
                    }
                }
            }
        ])
        .controller('TeamController', [
            '$scope',
            '$rootScope',
            'TeamService',
            function ($scope, $rootScope, service) {

                $scope.categories = [{
                    type: "1",
                    name: "策划经理"
                }, {
                        type: "2",
                        name: "小蜜蜂"
                    }];

                function refresh(cb) {
                    $scope.proj_id = $scope.$parent.curProjectId;

                    if ($scope.proj_id) {
                        angular.forEach($scope.categories, function (cat, index) {
                            $scope.categories[index].userList = [];
                        });
                        $scope.$emit('refresh');
                    }
                }


                $scope.$on('projChange', function (e, projId) {
                    $scope.proj_id = projId;
                    refresh();
                });

                $scope.teamUsersImporter = {
                    onDialogShow: function ($dialog, scope) {
                        scope.proj_id = $scope.proj_id;
                        scope.exportTemplate = function () {
                            util.download(service.getTemplateUrl());
                        };
                        scope.onUploadStatusChanged = function (statusData) {
                            switch (statusData.status) {
                                case 'error':
                                    var data = statusData.response.data;
                                    if (data && data.length) {
                                        var msg = "";
                                        for (var i = 0; i < data.length; i++) {
                                            var user = data[i];
                                            msg += '"' + user.user_name + '" 创建出错，原因： ' + user.err + '<br>';
                                        }

                                        $rootScope.$emit('error', msg, true);
                                        
                                        angular.forEach($scope.categories, function (cat, index) {
                                            $scope.categories[index].userList = [];
                                        });
                                        $scope.$emit('refresh',{pageIndex:1});
                                    }

                                    break;
                                case 'success':
                                    $rootScope.$emit('httpRequestSuccess', "上传成功");
                                    angular.forEach($scope.categories, function (cat, index) {
                                        $scope.categories[index].userList = [];
                                    });
                                    $scope.$emit('refresh',{pageIndex:1});
                                    $dialog.close();
                                    break;
                            }
                        };
                    },
                    save: function ($dialog, scope) {
                        scope.uploaderModel.upload();
                        return false;
                    }
                };

                $scope.userSelector = {
                    init: function ($dialog, scope) {
                        scope.pager = {
                            pageIndex: 0,
                            pageSize: 10,
                            changed: function (pageIndex) {
                                scope.checker.all = false;
                                
                                if (scope.keyword) {
                                    $scope.searchMembers({
                                        keyword: scope.keyword,
                                        pageIndex: pageIndex
                                    })
                                        .then(function (res) {
                                            scope.userList = res.data.data;
                                            scope.pager.total = res.data.total;
                                            scope.pager.pageIndex = pageIndex || 1;
                                        })
                                    return;
                                }
                                $scope.getMembers({
                                    pageIndex: pageIndex,
                                    pageSize: scope.pager.pageSize
                                })
                                    .then(function (res) {
                                        scope.userList = res.data.data;
                                        scope.pager.pageIndex = pageIndex;
                                        scope.pager.total = res.data.total;
                                    })
                            }
                        };

                        scope.checker = {
                            all: false,
                            checkAll: function () {

                                for (var i = 0; i < scope.pager.pageSize; i++) {
                                    if (scope.userList[i]) {
                                        scope.userList[i].checked = scope.checker.all;
                                    }
                                }

                                scope.checker.selected = scope.checker.all;
                            },
                            check: function (user) {
                                var all = true;
                                scope.checker.selected = false;

                                for (var i = 0; i < scope.pager.pageSize; i++) {

                                    if (scope.userList[i]) {
                                        if (scope.userList[i].checked) {
                                            scope.checker.selected = true;
                                        } else {
                                            all = false;
                                        }
                                    }

                                }

                                scope.checker.all = all;
                            }
                        };

                        scope.search = function () {
                            scope.keyword = scope.search_text;
                            scope.checker.all = false;
                            $scope.searchMembers({
                                keyword: scope.keyword
                            })
                                .then(function (res) {
                                    scope.userList = res.data.data;
                                    scope.pager.total = res.data.total;
                                    scope.pager.pageIndex = 1;
                                })
                        }

                        $scope.getMembers()
                            .then(function (res) {
                                scope.userList = res.data.data;
                                scope.pager.total = res.data.total;
                            })
                    },
                    save: function ($dialog, scope) {
                        var selects = [];
                        for (var i = 0; i < scope.userList.length; i++) {
                            if (scope.userList[i].checked) {
                                selects.push(scope.userList[i].user_id);
                            }
                        }
                        $scope.createUser($dialog, selects);
                    }
                };
                $scope.category = $scope.categories[0];

                $scope.switchCate = function (index) {
                    $scope.category = $scope.categories[index];
                };

                $scope.getUsers = function (opts) {
                    opts = opts || {};

                    var pageIndex = opts.pageIndex || $scope.category.pager.pageIndex || 1
                    
                    service.getMemberList({
                        search: {
                            "page_index": pageIndex,
                            "page_size": opts.pageSize || 10,
                            "proj_id": $scope.proj_id,
                            "type": $scope.category.type
                        }
                    })
                        .then(function (res) {
                            $scope.category.userList = res.data.data;
                            $scope.category.pager.total = res.data.total;
                            $scope.category.checker.all = false;
                            $scope.category.checker.selected = false;
                            $scope.category.pager.pageIndex = pageIndex;
                        })
                };

                $scope.getMembers = function (opts) {
                    opts = opts || {};

                    return service.getMembers({
                        search: {
                            "page_index": opts.pageIndex || 1,
                            "page_size": opts.pageSize || 10,
                            "proj_id": $scope.proj_id,
                            "type": $scope.category.type
                        }
                    })
                };

                $scope.searchMembers = function (opts) {
                    opts = opts || {};

                    return service.searchMembers({
                        search: {
                            "page_index": opts.pageIndex || 1,
                            "page_size": opts.pageSize || 10,
                            "proj_id": $scope.proj_id,
                            "type": $scope.category.type,
                            "keyword": opts.keyword || ""
                        }
                    })
                }

                $scope.updateUser = function ($data, $dialog) {
                    if (!$data || !$data.team_name) {
                        $rootScope.$emit('error', '数据填写不完整')
                        return false;
                    }
                    service.updateUser({
                        data: {
                            "proj_id": $scope.proj_id,
                            "user_type": $scope.category.type,
                            user_id: $data.user_id,
                            team_name: $data.team_name
                        }
                    }).then(function (res) {
                        $scope.$emit('refresh');
                        $dialog.close();
                    });

                    return false;
                };

                $scope.createUser = function ($dialog, selects) {

                    service.createUser({
                        data: {
                            "proj_id": $scope.proj_id,
                            "type": $scope.category.type,
                            "user_ids": selects.join(',')
                        }
                    }).then(function (res) {
                        $scope.$emit('refresh',{pageIndex:1});
                        $dialog.close();
                    });

                    return false;
                };

                $scope.deleteUser = function (user) {
                    service.deleteUser({
                        data: {
                            "proj_id": $scope.proj_id,
                            "type": $scope.category.type,
                            user_ids: user.user_id
                        }
                    }).then(function (res) {
                        $scope.$emit('refresh',{pageIndex:1});
                    });
                };

                $scope.deleteUsers = function () {
                    var selects = [];
                    for (var i = 0; i < $scope.category.pager.pageSize; i++) {
                        if ($scope.category.userList[i] && $scope.category.userList[i].checked) {
                            selects.push($scope.category.userList[i].user_id)
                        }
                    }

                    if (!selects.length) {
                        return;
                    }

                    service.deleteUser({
                        data: {
                            "proj_id": $scope.proj_id,
                            "type": $scope.category.type,
                            user_ids: selects.join(',')
                        }
                    }).then(function (res) {
                        if (res.retMsg) {
                            $rootScope.$emit('httpRequestError',res.retMsg);
                            //return;
                        }
                        $scope.$emit('refresh',{pageIndex:1});
                    });
                    
                };

                angular.forEach($scope.categories, function (cat, index) {
                    $scope.categories[index].pager = {
                        pageIndex: 0,
                        pageSize: 10,
                        changed: function (pageIndex) {
                            $scope.getUsers({
                                pageIndex: pageIndex,
                                pageSize: $scope.category.pager.pageSize
                            })
                        }
                    };

                    $scope.categories[index].checker = {
                        all: false,
                        checkAll: function () {

                            for (var i = 0; i < $scope.category.pager.pageSize; i++) {
                                if ($scope.category.userList[i]) {
                                    $scope.category.userList[i].checked = $scope.category.checker.all;
                                }
                            }

                            $scope.category.checker.selected = $scope.category.checker.all;
                        },
                        check: function (user) {
                            var all = true;
                            $scope.category.checker.selected = false;

                            for (var i = 0; i < $scope.category.pager.pageSize; i++) {

                                if ($scope.category.userList[i]) {
                                    if ($scope.category.userList[i].checked) {
                                        $scope.category.checker.selected = true;
                                    } else {
                                        all = false;
                                    }
                                }

                            }

                            $scope.category.checker.all = all;
                        }
                    };
                });

                $scope.$watch('category', function (cat, old) {
                    if (cat.type !== old.type) {
                        if (!$scope.category.userList || !$scope.category.userList.length) {
                            $scope.$emit('refresh');
                        }
                    }
                });

                $scope.$on('refresh',function(e,data){
                    if (data) {
                        $scope.category.pager.pageIndex = 1;
                    }
                    $scope.getUsers(data);
                });
                refresh();
            }
        ])

});
